import { computed, onMounted, onUnmounted, ref } from "vue";

// 可选的三种操作
const options = ["all", "active", "completed"];

export default function filterTodos(todoListRef) {
	let optionRef = ref("all");

	function hashChangeHandle() {
		let hash = location.hash.replace(/#\/?/, "");
		if (!options.includes(hash)) {
			// 如果hash值不在options中，则默认为all
			location.hash = "all";
		} else {
			optionRef.value = hash;
		}
	}

	function filter(todoListRef, type) {
		if (type === "all") {
			// 如果type值为all，则返回所有todo
			return todoListRef.value;
		} else if (type === "active") {
			// active，则返回未完成的todo
			return todoListRef.value.filter((item) => !item.isFinish);
		} else if (type === "completed") {
			// completed,显示已完成的todo
			return todoListRef.value.filter((item) => item.isFinish);
		} else {
			// 如果type值不在options中，则默认为all
			return todoListRef.value;
		}
	}

	onMounted(() => {
		// 当组件挂载时需要做的事情
		hashChangeHandle();
		window.addEventListener("hashchange", hashChangeHandle);
	});
	onUnmounted(() => {
		// 当组件卸载时需要做的事情
		window.removeEventListener("hashchange", hashChangeHandle);
	});

	const filterTodosRef = computed(() => {
		return filter(todoListRef, optionRef.value);
	});

	const pendingTodosRef = computed(() => {
		return filter(todoListRef, "active");
	});

	const completedTodosRef = computed(() => {
		return filter(todoListRef, "completed");
	});

	return {
		optionRef,
		filterTodosRef,
		pendingTodosRef,
		completedTodosRef,
	};
}
